import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { login, getInfo, logout , phoneLogin } from '@/api/login'
import { getUserResource } from '@/api/system';
import { ACCESS_TOKEN , USER_TYPE } from '@/store/mutation-types'
import { welcome } from '@/utils/util'

storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 账号密码登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          console.log(response,'response')
          const result = response
          if(result.success){
            sessionStorage.setItem(ACCESS_TOKEN, result.data.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
            var userSubType = result.data.userSubType
            if(result.data.userSubType == 4){
              userSubType = 2
            }
            if(result.data.userSubType == 5){
              userSubType = 3
            }
            sessionStorage.setItem(USER_TYPE,userSubType,)
            sessionStorage.setItem('userPhone',result.data.mobile,)
            sessionStorage.setItem('userName',result.data.userName,)
            sessionStorage.setItem('customerId',result.data.customerId,)
            sessionStorage.setItem('laborCompanyId',result.data.laborCompanyId,)
            // localStorage.setItem('hasLogin',result.data.hasLogin)
            commit('SET_TOKEN', result.data.token)
            commit('SET_INFO', result.data)
            commit('SET_AVATAR', result.data.avatar)
            resolve(response)
          }else{
            console.log('走了这里')
            reject(response.errMessage)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 验证码登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        phoneLogin(userInfo).then(response => {
          console.log(response,'response')
          const result = response
          if(response.success){
              sessionStorage.setItem(ACCESS_TOKEN, result.data.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
              var userSubType = result.data.userSubType
              if(result.data.userSubType == 4){
                userSubType = 2
              }
              if(result.data.userSubType == 5){
                userSubType = 3
              }
              sessionStorage.setItem(USER_TYPE,userSubType,)
              sessionStorage.setItem('userPhone',result.data.mobile,)
              sessionStorage.setItem('userName',result.data.userName,)
              sessionStorage.setItem('customerId',result.data.customerId,)
              sessionStorage.setItem('laborCompanyId',result.data.laborCompanyId,)
              // localStorage.setItem('hasLogin',result.data.hasLogin)
              commit('SET_TOKEN', result.data.token)
              commit('SET_INFO', result.data)
              commit('SET_AVATAR', result.data.avatar)
              resolve(response)
          }else{
            reject(response.errMessage)
          }
        }).catch(error => {
          console.log(error,'error')
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        // console.log(sessionStorage.getItem(USER_TYPE),'sessionStorage.getItem(USER_TYPE)')
        // commit('SET_ROLES', [sessionStorage.getItem(USER_TYPE)])
        // resolve([sessionStorage.getItem(USER_TYPE)])
        getUserResource().then(response => {
          const result = response.data

          // if (result.role && result.role.permissions.length > 0) {
          //   const role = result.role
          //   role.permissions = result.role.permissions
          //   role.permissions.map(per => {
          //     if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
          //       const action = per.actionEntitySet.map(action => { return action.action })
          //       per.actionList = action
          //     }
          //   })
          //   role.permissionList = role.permissions.map(permission => { return permission.permissionId })
          //   commit('SET_ROLES', result.role)
          //   commit('SET_INFO', result)
          // } else {
          //   reject(new Error('getInfo: roles must be a non-null array !'))
          // }

          // commit('SET_NAME', { name: result.name, welcome: welcome() })
          // commit('SET_AVATAR', result.avatar)
          commit('SET_ROLES', result)
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROUTERS', [])
          commit('SET_ROLES', [])
          // storage.remove(ACCESS_TOKEN)
          // storage.clearAll();
          // sessionStorage.clear();
          resolve()
        }).catch((err) => {
          console.log('logout fail:', err)
          // resolve()
        }).finally(() => {
        })
      })
    }

  }
}

export default user
